package com.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * Created by lanxiaolong on 2019/1/8.
 */
public class EchoClient {
    private final String host = "127.0.0.1";
    private final int port = 9999;

    public static void main(String[] args) throws Exception {
        for (int i=0; i<5; i++){
            new EchoClient().start();
        }
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)  // 适用于NIO传输的Channel类型
                    // 设置服务器的InetSocketAddress
                    .remoteAddress(new InetSocketAddress(host, port))
                    // 在创建Channel的时候ChannelPipeline中添加一个EchoClientHandler实例
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture f = b.connect().sync();  // 连接到远程节点，阻塞等待直到连接完成
            f.channel().closeFuture().sync();  // 阻塞直到Channel关闭
        } finally {
            // 关闭线程池并且释放所有资源
            group.shutdownGracefully().sync();
        }
    }
}
